package com.oocl.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.xml.ws.handler.MessageContext;

import com.oocl.msgProcess.ChatProcess;
import com.oocl.msgProcess.ShakeProcess;
import com.oocl.tm.log4j.Log4j;
import com.oocl.tm.protocol.MsgPackage;
import com.oocl.tm.protocol.Operation;
import com.oocl.tm.ui.ChatFrame;

public class ClientListener extends Thread{
	
	private Lock lock = new ReentrantLock();
	
	private Socket socket;
	private String name;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private JTextArea chatTa;
	private ChatFrame win;
	private JPanel panRight;
	private ButtonGroup btnGroup;
	
	public ClientListener(Socket socket, String name, ObjectOutputStream out, ObjectInputStream in, JTextArea chatTa, ChatFrame win, JPanel panRight, ButtonGroup btnGroup){
		this.socket = socket;
		this.name = name;
		this.out = out;
		this.in = in;
		this.chatTa = chatTa;
		this.win = win;
		this.panRight = panRight;
		this.btnGroup = btnGroup;
		
	}
	
	@Override
	public void run() {
		
		try {
			InputStream zin = socket.getInputStream();
			in = new ObjectInputStream(zin);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		while(ChatFrame.flag){
			try {
					lock.lock();
					if(ChatFrame.flag){
						
						if(in!=null){
						MsgPackage msg = (MsgPackage) in.readObject();
						Log4j.getLogger().info(name + "收到服务器的消息：" + msg.toString());
						switch (msg.getOperation()) {
						case CHAT:
							ChatProcess.chatProcess(msg, chatTa ,name);
							break;
						case SHAKE:
							new ShakeProcess(win);
							break;
						case EXIT:
							System.out.println("与服务端连接异常，客户端即将推出！");
							System.exit(0);
							break;	
						case NOTIFY:
							ChatProcess.notiryProcess(msg, btnGroup, name);
							break;
						}
						}
					}
				
				
				
			} catch (ClassNotFoundException | IOException e) {
				
				int n=JOptionPane.showConfirmDialog(null, "Connect Error with Server!!!","Error",JOptionPane.DEFAULT_OPTION);
				if(n==0){
					System.out.println("Server Boom");
					System.exit(0);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				lock.unlock();
			}
			
			
			
		}
	}
	
}
